#include "rayintersections.h"
#include "line.h"


bool belongs(point_t const & ray_start, polygon_t const & polygon)
{
    size_t counter = 0;
    for(size_t i = 0; i < polygon.size(); ++i)
    {
        contour_t contour = polygon[i];
        for(size_t j = 0; j < contour.size(); ++j)
        {
            point_t begin = (j == 0) ? contour[contour.size() - 1] : contour[j - 1];
            point_t end = contour[j];
            ray_state state = intersects_segment(ray_start, begin, end);
            if(state == INTERSECTS)
            {
                ++counter;
            }
            if(state == BEGINS_ON_SEGMENT)
            {
                return true;
            }
        }
    }
    return (counter % 2) == 1;
}

ray_state intersects_segment(point_t const & ray_start, point_t const & begin, point_t const & end)
{
    if (begin.y == end.y)
        return NOT_INTERSECTS;
    point_t const & smaller = (end.y < begin.y) ? end : begin;
    if (ray_start.y == smaller.y)
        return NOT_INTERSECTS;
    if (ray_start.y < begin.y && ray_start.y < end.y)
        return NOT_INTERSECTS;
    if (ray_start.y > begin.y && ray_start.y > end.y)
        return NOT_INTERSECTS;
    if (ray_start.x < begin.x && ray_start.x < end.x)
        return NOT_INTERSECTS;
    line_t line(begin, end);
    point_pos position = line.classify(ray_start);
    if (position == LEFT)
        return NOT_INTERSECTS;
    if (position == ON)
        return BEGINS_ON_SEGMENT;
    return INTERSECTS;
}
